package j_util.sorters;

import java.util.Comparator;
import java.util.List;

public class HeapsortTernary extends AbstractHeapsort {

    private void sink(List list, int k, int n) {
        while (3 * k <= n) {
            int j = 3 * k;
            if (j < n && less(list.get(j), list.get(j + 1), comparator)) {//j<j+1
                j++;
                if (j < n && less(list.get(j), list.get(j + 1), comparator)) {//j+1<j+2
                    j++;
                }
            } else {//j>j+1
                if (j + 1 < n && less(list.get(j), list.get(j + 2), comparator)) {
                    j = j + 2;
                }
            }
            if (!less(list.get(k), list.get(j), comparator)) {
                break;
            }
            exchange(list, k, j);
            k = j;
        }
    }

    private void printList(List list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.print("" + list.get(i).toString() + ",");
        }
        System.out.println("");
    }

    public <T> void sort(List<T> list, int left, int right, Comparator<T> c) {
        if (list == null || right <= left) {
            return;
        }
        comparator = c;
        printList(list);
        for (int k = right / 3; k >= left; k--) {
            sink(list, k, right);
            printList(list);
        }
        while (right > left) {
            exchange(list, left, right);
            printList(list);
            sink(list, left, --right);
        }
    }

    public String getName() {
        return "HeapSortTernary";
    }

    public <T> void sort(List<T> list, Comparator<T> comparator) {
        this.comparator = comparator;
        sort(list, 0, list.size() - 1, comparator);
    }
}
